package cn.schoolwow.quickdao.module.initial.flow.datasource;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.exception.SQLRuntimeException;
import cn.schoolwow.quickdao.domain.provider.DatabaseProvider;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.List;

public class InitialQuickDAOConfigDataSourceFlow implements BusinessFlow {
    private Logger logger = LoggerFactory.getLogger(InitialQuickDAOConfigDataSourceFlow.class);

    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DataSource dataSource = flowContext.checkData("dataSource", DataSource.class);
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        List<DatabaseProvider> databaseProviderList = (List<DatabaseProvider>) flowContext.checkData("databaseProviderList");

        try (Connection connection = dataSource.getConnection();){
            connection.setAutoCommit(false);

            String jdbcUrl = connection.getMetaData().getURL();
            for (DatabaseProvider databaseProvider : databaseProviderList) {
                if (jdbcUrl.contains("jdbc:" + databaseProvider.name())) {
                    quickDAOConfig.databaseContext.databaseProvider = databaseProvider;
                    break;
                }
            }
            if (null == quickDAOConfig.databaseContext.databaseProvider) {
                throw new IllegalArgumentException("不支持的数据库类型!jdbcUrl:" + jdbcUrl);
            }
            quickDAOConfig.databaseContext.databaseName = connection.getCatalog();
            logger.info("[数据源]类型:{},地址:{}", quickDAOConfig.databaseContext.databaseProvider.name(), jdbcUrl);
        } catch (Exception e) {
            throw new SQLRuntimeException(e);
        }
        quickDAOConfig.databaseContext.dataSource = dataSource;
    }

    @Override
    public String name() {
        return "初始化全局配置的数据库连接池信息";
    }
}
